﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
namespace vstest1
{
    //此类可以用来定义出具体的uart对象，之后的uart通信都是根据定义出来的对象的属性与方法进行的
    //根据定义出来的对象的属性与方法进行的
    public partial class Uart
    {
        public static SerialPort ComPort = new SerialPort();//真正的uart对象
        public static byte[] DataRingBuf = new byte[2000];//接收数据buffer

        public struct RcvBuf
        {
            public static int headPos;
            public static int tailPos;
        }

        public static string[] GetActiveComPorts()
        {
            return SerialPort.GetPortNames();//检查当前active的uart
        }
        public static object[] GetBaud()//返回数组--波特率
        {
            return new object[] { "9600", "115200" };
        }

        /// <summary>
        /// 钩子函数，uart对象接收到数据就会调用--回调函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void Port_DataRecieved(object sender, SerialDataReceivedEventArgs e)
        {
            int readCnt = ComPort.BytesToRead;//收到数据的字节数量
            if (RcvBuf.tailPos < 1900)
            {
                //RcvBuf本身是个结构体，但是也可以直接当作变量去使用--神奇的C#
                ComPort.Read(DataRingBuf, RcvBuf.tailPos, readCnt);//将uart缓冲区的数据全部存到DataRingBuf 字节数组中
                RcvBuf.tailPos += readCnt;
                Console.WriteLine(DataRingBuf);
            }
        }

        public static void OpenPort(string portName, Int32 baudRate)
        {
            ComPort.DataReceived += new SerialDataReceivedEventHandler(Port_DataRecieved);//关联钩子函数
            ComPort.PortName = portName;
            ComPort.BaudRate = baudRate;
            ComPort.Parity = Parity.None;
            ComPort.StopBits = StopBits.One;
            ComPort.DataBits = 8;
            ComPort.Encoding = System.Text.Encoding.GetEncoding("GB2312");//注意还要给uart的Encoding属性赋值
            ComPort.Open();
        }


    }

}
